/*
 * Projet industriel VAMP 2012 
 */
package com.vampmobile.android.tools;

/**
 * @author Dida
 *
 */
import java.io.File;
import java.io.FileNotFoundException;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.os.ParcelFileDescriptor;
import android.util.Log;

public class FileDownload extends Thread {

	public static final String TAG = "FileDownload";
	private long downloadID;
	protected DownloadManager downloadManager;
	private String link;
	private Context context;
	String name;
	String type;

	public FileDownload(Context context, String link, String name, String type) {
		this.name = name;
		this.link = link;
		this.context = context;
		this.type = type;
		Environment.getExternalStoragePublicDirectory(
				Environment.DIRECTORY_DOWNLOADS).mkdirs();
		downloadManager = (DownloadManager) context
				.getSystemService(Context.DOWNLOAD_SERVICE);
		IntentFilter intentFilter = new IntentFilter(
				DownloadManager.ACTION_DOWNLOAD_COMPLETE);
		context.registerReceiver(downloadReceiver, intentFilter);
	}

	@Override
	public void run() {

		File file = new File(
				Environment
						.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
				name);
		if (file.exists()) {
			openFile(file);
		}

		Uri uri = Uri.parse(link);
		DownloadManager.Request request = new DownloadManager.Request(uri)
				.setAllowedNetworkTypes(
						DownloadManager.Request.NETWORK_WIFI
								| DownloadManager.Request.NETWORK_MOBILE)
				.setAllowedOverRoaming(false)
				.setTitle(name)
				.setShowRunningNotification(true)
				.setDestinationInExternalPublicDir(
						Environment.DIRECTORY_DOWNLOADS, name);
		downloadID = downloadManager.enqueue(request);
	}

	private BroadcastReceiver downloadReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context arg0, Intent arg1) {
			// TODO Auto-generated method stub
			DownloadManager.Query query = new DownloadManager.Query();
			query.setFilterById(downloadID);
			Cursor cursor = downloadManager.query(query);

			if (cursor.moveToFirst()) {
				int columnIndex = cursor
						.getColumnIndex(DownloadManager.COLUMN_STATUS);
				int status = cursor.getInt(columnIndex);
				int columnReason = cursor
						.getColumnIndex(DownloadManager.COLUMN_REASON);
				int reason = cursor.getInt(columnReason);

				if (status == DownloadManager.STATUS_SUCCESSFUL) {

					// Retrieve the saved download id

					ParcelFileDescriptor file;
					try {
						file = downloadManager.openDownloadedFile(downloadID);
						openFile(new File(
								Environment
										.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
								name));
						Log.i(TAG, "File Downloaded: " + file.toString());
					} catch (FileNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						Log.i(TAG, e.toString());
					}

				} else if (status == DownloadManager.STATUS_FAILED) {
					Log.i(TAG, "FAILED!\n" + "reason of " + reason);
				} else if (status == DownloadManager.STATUS_PAUSED) {
					Log.i(TAG, "PAUSED!\n" + "reason of " + reason);
				} else if (status == DownloadManager.STATUS_PENDING) {
					Log.i(TAG, "PENDING!");
				} else if (status == DownloadManager.STATUS_RUNNING) {
					Log.i(TAG, "RUNNING!");
				}
			}
		}
	};

	protected void openFile(File fileName) {
		Intent view = new Intent(Intent.ACTION_VIEW);
		view.setDataAndType(Uri.fromFile(fileName), type);
		context.startActivity(view);
	}

}